#include <stdio.h>
#include <assert.h>
#include "Thread.h"
#if __IS_WIN__
#define snprintf _snprintf
#endif

typedef struct _ThreadParam {
	int index;
	ThreadLockType *lock;
}_STThreadParam;
void writeFile(void *param) {
	_STThreadParam *threadParam = (_STThreadParam *)param;
	int nIndex = threadParam->index;
	ThreadLockType *lock = threadParam->lock;
	char buffer[32] = {0};
	FILE *f = NULL;
	const char * fileName = "test.txt";
	
	int ret = Thread::lock(lock);
	assert(ret == 0);
#if __IS_WIN__
	if ((fopen_s(&f,fileName,"ab+")) != 0) {
#else
	if ((f = fopen(fileName,"ab+")) == NULL) {
#endif
			printf("open log file [%s] error\n",fileName);
			goto clear;
	}
	snprintf(buffer,31,"writen by thread[%d]\n",nIndex);
	fwrite(buffer,sizeof(char),sizeof(buffer),f);
	fclose(f);
clear:
	Thread::unlock(lock);
	
}

int main() {
	ThreadLockType lock;
	ThreadRun run = writeFile;
	Thread::createLock(&lock);
	for(int i=0;i<5;i++) {
		_STThreadParam param;
		Thread t(run);
		param.index = i;
		param.lock = &lock;
		t.start(&param);
		t.join();
	}
	return 0;
	
}
